package com.sniff.atp.service.goods;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.constant.LoginConstant;
import com.sniff.atp.dto.ClientLoginDTO;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.dto.SystemLoginDTO;
import com.sniff.atp.dto.request.CreateProductDTO;
import com.sniff.atp.dto.request.UserInfo;
import com.sniff.atp.enums.api.OrderAPI;
import com.sniff.atp.service.login.ClientLoginService;
import com.sniff.atp.service.order.OEMOrderService;
import com.sniff.atp.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class GoodsService {
    @Autowired
    private OEMOrderService oemOrderService;

    @Autowired
    private ClientLoginService clientLoginService;

    /**
     * 创建线下商品
     */
    public JSONObject addOfflineProduct(CreateProductDTO createProductDTO) {
        SystemLoginDTO systemLoginDTO = LoginConstant.systemLoginDTO;
        Integer offlineDirectSaleFlag =createProductDTO.getOfflineDirectSaleFlag();
        //创建线下商品
        String productCode = "offLineSpu" + RandomUtil.numberString(10);
        String productTitle = "线下商品工厂" + RandomUtil.numberString(10);
        String supplierSpu = "supplierSpu" + RandomUtil.numberString(10);


        JSONObject params = JsonUtil.readJson("product/OfflineProductReq.json");
        params.put("offlineDirectSaleFlag", offlineDirectSaleFlag);
        params.put("productTitle", productTitle);
        params.put("supplierSpu", supplierSpu);
        params.put("productCode", productCode);
        new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(OrderAPI.ADD_OFFLINE_PRODUCT.getApi(), params);

        //获取线下商品详情
        List<JSONObject> sql025 = DBUtil.select("PRODUCT-根据spu查询sku", new ContentDTO("",productCode));
        List<String> productSkuList = sql025.stream()
                .map(obj -> obj.getString("product_sku"))
                .collect(Collectors.toList());
        JSONObject productInfo = new JSONObject();
        productInfo.put("productTitle",productTitle);
        productInfo.put("productCode",productCode);
        productInfo.put("productUrl","https://master-s.theckb.com/goods/" + productCode);
        productInfo.put("offlineDirectSaleFlag",offlineDirectSaleFlag==1 ? "直营":"代采");
        productInfo.put("productSkuList",new JSONArray(productSkuList));

        return productInfo;
    }

    /**
     * 创建OEM商品
     */
    public JSONObject addOEMProduct(CreateProductDTO createProductDTO) {
        //登录客户端
        UserInfo userInfo = createProductDTO.getUserInfo();
//        ClientLoginDTO clientLoginDTO = clientLoginService.loginByUserInfo(userInfo);
        String customerShopName = userInfo.getCustomerShopName();
        ClientLoginDTO clientLoginDTO = clientLoginService.loginByCustomerShopName(customerShopName);
        //登录后台
        SystemLoginDTO systemLoginDTO = LoginConstant.systemLoginDTO;
//      OEM商品类型
        Integer oemProductClassificationId = createProductDTO.getOemProductClassificationId();
        //创建寻源任务
        String searchSourceOrderId = oemOrderService.createByVo(clientLoginDTO, oemProductClassificationId);
        //提出寻源任务
        oemOrderService.publish(clientLoginDTO, searchSourceOrderId);
        //获取寻源单详情
        JSONObject searchSourceOrderDetail = oemOrderService.searchSourceOrderDetail(systemLoginDTO, searchSourceOrderId);
        String searchSourceOrderNo = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("searchSourceOrderNo");
        //翻译寻源单
        oemOrderService.userUpdateByVo(systemLoginDTO, searchSourceOrderId);
        //接单
        oemOrderService.acceptOrder(systemLoginDTO, searchSourceOrderId);
        //分配
        oemOrderService.distributeOrder(systemLoginDTO, searchSourceOrderId);
        //采购报价
        oemOrderService.batchReportPurchasePrice(searchSourceOrderId);
        //寻源单报价详情（后台）
        List<JSONObject> currentPriceList = oemOrderService.getSupplierPriceListWithStatus(systemLoginDTO, searchSourceOrderNo);
        //审核报价通过（后台）
        currentPriceList.stream().forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.approvePurchasePricePass(systemLoginDTO, supplierPriceId);
        });

        //构建保存销售价参数
        JSONArray savePriceList = new JSONArray();
        currentPriceList.stream().forEach(obj -> {
            JSONObject savePrice = new JSONObject();
            savePrice.put("containTaxFlag", 1);
            savePrice.put("customerSamplePrice", 16.66);
            savePrice.put("searchSourceId", obj.getString("searchSourceOrderId"));
            savePrice.put("searchSourceOrderSupplierPriceId", obj.getString("searchSourceOrderSupplierPriceId"));
            JSONArray fillSellPriceItemList = new JSONArray();
            JSONArray reportePurchasePriceItemJSONArray =obj.getJSONArray("reportePurchasePriceItemList");
            List<JSONObject> reportePurchasePriceItemList = (List<JSONObject>) reportePurchasePriceItemJSONArray.stream().collect(Collectors.toList());
            reportePurchasePriceItemList.stream().forEach(obj1 -> {
                JSONObject sellPriceItem = new JSONObject();
                sellPriceItem.put("searchSourceOrderSupplierPriceItemId", obj1.getString("searchSourceOrderSupplierPriceItemId"));
                sellPriceItem.put("sellPrice", obj1.getBigDecimal("purchasePrice").add(new BigDecimal(1.11)));
                fillSellPriceItemList.add(sellPriceItem);
            });
            savePrice.put("fillSellPriceItemList", fillSellPriceItemList);
            savePriceList.add(savePrice);
        });

        //保存销售价（后台）
        oemOrderService.doBatchSavePrice(systemLoginDTO, savePriceList);

        //提交销售价（后台）
        oemOrderService.batchFillSellPrice(systemLoginDTO, savePriceList);

        //复审通过（后台）
        currentPriceList.forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.recheckPass(systemLoginDTO, supplierPriceId);
        });
        //翻译报价
        currentPriceList.forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.translate(systemLoginDTO, supplierPriceId);
        });
        //提交报价
        oemOrderService.ddReportSellPrice(systemLoginDTO,searchSourceOrderId);

        //获取寻源单详情
        searchSourceOrderDetail = oemOrderService.searchSourceOrderDetail(systemLoginDTO, searchSourceOrderId);

        //构建返回值
        String classificationName = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("classificationName");
        Integer orderStatus = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getInteger("orderStatus");
        String customerShopId = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("customerShopId");
        String bizType = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("bizType");
        String searchSourceOrderSupplierPriceId = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("searchSourceOrderSupplierPriceId");
        JSONObject productInfo = new JSONObject();
        productInfo.put("searchSourceOrderId",searchSourceOrderId);
        productInfo.put("searchSourceOrderNo",searchSourceOrderNo);
        productInfo.put("searchSourceOrderSupplierPriceId",searchSourceOrderSupplierPriceId);
        productInfo.put("classificationName",classificationName);
        productInfo.put("orderStatus",orderStatus);
        productInfo.put("customerShopId",customerShopId);
        productInfo.put("bizType",bizType);
        JSONArray searchSourceOrderSkuList = searchSourceOrderDetail.getJSONObject("data").getJSONArray("searchSourceOrderSkuList");
        Stream<JSONObject> jsonStream = searchSourceOrderSkuList.stream();
        JSONArray skuList =jsonStream.map(obj -> {
            JSONObject newObj  = new JSONObject();
            newObj.put("productSku", obj.getString("productSku"));
            return newObj;
        }) .collect(JSONArray::new, JSONArray::add, JSONArray::add);
        productInfo.put("skuList",skuList);

        return productInfo;
    }

    /**
     * 创建OEM商品
     */
    public JSONObject addOEMProductPre(CreateProductDTO createProductDTO) {
        //登录客户端
        UserInfo userInfo = createProductDTO.getUserInfo();
        ClientLoginDTO clientLoginDTO = clientLoginService.loginByUserInfo(userInfo);

        //登录后台
        SystemLoginDTO systemLoginDTO = LoginConstant.systemLoginDTO;
//      OEM商品类型
        Integer oemProductClassificationId = createProductDTO.getOemProductClassificationId();
        //创建寻源任务
        String searchSourceOrderId = oemOrderService.createByVo(clientLoginDTO, oemProductClassificationId);
        //提出寻源任务
        oemOrderService.publish(clientLoginDTO, searchSourceOrderId);
        //获取寻源单详情
        JSONObject searchSourceOrderDetail = oemOrderService.searchSourceOrderDetail(systemLoginDTO, searchSourceOrderId);
        String searchSourceOrderNo = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("searchSourceOrderNo");
        //翻译寻源单
        oemOrderService.userUpdateByVo(systemLoginDTO, searchSourceOrderId);
        //接单
        oemOrderService.acceptOrder(systemLoginDTO, searchSourceOrderId);
        //分配
        oemOrderService.distributeOrder(systemLoginDTO, searchSourceOrderId);
        //采购报价
        oemOrderService.batchReportPurchasePrice(searchSourceOrderId);
        //寻源单报价详情（后台）
        List<JSONObject> currentPriceList = oemOrderService.getSupplierPriceListWithStatus(systemLoginDTO, searchSourceOrderNo);
        //审核报价通过（后台）
        currentPriceList.stream().forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.approvePurchasePricePass(systemLoginDTO, supplierPriceId);
        });

        //构建保存销售价参数
        JSONArray savePriceList = new JSONArray();
        currentPriceList.stream().forEach(obj -> {
            JSONObject savePrice = new JSONObject();
            savePrice.put("containTaxFlag", 1);
            savePrice.put("customerSamplePrice", 16.66);
            savePrice.put("searchSourceId", obj.getString("searchSourceOrderId"));
            savePrice.put("searchSourceOrderSupplierPriceId", obj.getString("searchSourceOrderSupplierPriceId"));
            JSONArray fillSellPriceItemList = new JSONArray();
            JSONArray reportePurchasePriceItemJSONArray =obj.getJSONArray("reportePurchasePriceItemList");
            List<JSONObject> reportePurchasePriceItemList = (List<JSONObject>) reportePurchasePriceItemJSONArray.stream().collect(Collectors.toList());
            reportePurchasePriceItemList.stream().forEach(obj1 -> {
                JSONObject sellPriceItem = new JSONObject();
                sellPriceItem.put("searchSourceOrderSupplierPriceItemId", obj1.getString("searchSourceOrderSupplierPriceItemId"));
                sellPriceItem.put("sellPrice", obj1.getBigDecimal("purchasePrice").add(new BigDecimal(1.11)));
                fillSellPriceItemList.add(sellPriceItem);
            });
            savePrice.put("fillSellPriceItemList", fillSellPriceItemList);
            savePriceList.add(savePrice);
        });

        //保存销售价（后台）
        oemOrderService.doBatchSavePrice(systemLoginDTO, savePriceList);

        //提交销售价（后台）
        oemOrderService.batchFillSellPrice(systemLoginDTO, savePriceList);

        //复审通过（后台）
        currentPriceList.forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.recheckPass(systemLoginDTO, supplierPriceId);
        });
        //翻译报价
        currentPriceList.forEach(currentPrice -> {
            String supplierPriceId = currentPrice.getString("searchSourceOrderSupplierPriceId");
            oemOrderService.translate(systemLoginDTO, supplierPriceId);
        });
        //提交报价
        oemOrderService.ddReportSellPrice(systemLoginDTO,searchSourceOrderId);

        //获取寻源单详情
        searchSourceOrderDetail = oemOrderService.searchSourceOrderDetail(systemLoginDTO, searchSourceOrderId);

        //构建返回值
        String classificationName = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("classificationName");
        Integer orderStatus = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getInteger("orderStatus");
        String customerShopId = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("customerShopId");
        String bizType = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("bizType");
        String searchSourceOrderSupplierPriceId = searchSourceOrderDetail.getJSONObject("data").getJSONObject("searchSourceOrder").getString("searchSourceOrderSupplierPriceId");
        JSONObject productInfo = new JSONObject();
        productInfo.put("searchSourceOrderId",searchSourceOrderId);
        productInfo.put("searchSourceOrderNo",searchSourceOrderNo);
        productInfo.put("searchSourceOrderSupplierPriceId",searchSourceOrderSupplierPriceId);
        productInfo.put("classificationName",classificationName);
        productInfo.put("orderStatus",orderStatus);
        productInfo.put("customerShopId",customerShopId);
        productInfo.put("bizType",bizType);
        JSONArray searchSourceOrderSkuList = searchSourceOrderDetail.getJSONObject("data").getJSONArray("searchSourceOrderSkuList");
        Stream<JSONObject> jsonStream = searchSourceOrderSkuList.stream();
        JSONArray skuList =jsonStream.map(obj -> {
            JSONObject newObj  = new JSONObject();
            newObj.put("productSku", obj.getString("productSku"));
            return newObj;
        }) .collect(JSONArray::new, JSONArray::add, JSONArray::add);
        productInfo.put("skuList",skuList);

        return productInfo;
    }
//
//    /**
//     * 创建组合商品
//     */
//    public JSONObject addCombinationProduct(CreateProductDTO createProductDTO) {
//        JSONObject params = JsonUtil.readJson("order/cart/CombCreateAndAddCart.json");
//        params.put("combinationProductName", "COMB-NAME-AUTO-" + RandomUtil.numberString(5));
//        params.put("combinationProductProp", "COMB-PROP-AUTO-" + RandomUtil.numberString(5));
//        return new HttpClientUtil(Headers.setClientHeader(clientLoginDTO)).doPostJson(OrderAPI.COMB_CREATE_AND_CART.getApi(), params);
//    }

}
